<template>
    <div class="user-list">
      <!-- 过滤卡片 -->
      <el-card class="filter-card">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item label="公司名称">
            <el-input
                v-model="filterForm.companyName"
                placeholder="请输入公司名称"
                clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
                v-model="filterForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 150px"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="正常" :value="1"></el-option>
              <el-option label="封禁" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchUsers" :loading="loading">
              <i class="el-icon-search"></i> 查询
            </el-button>
            <el-button @click="resetFilter">
              <i class="el-icon-refresh"></i> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!--    广告主列表-->
      <el-card>
        <div slot="header" class="clearfix">
          <span>广告主列表</span>
          <el-button style="float: right; margin-top: -5px" type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </div>

        <el-table :data="adList" border fit style="width: 100%">
          <el-table-column prop="advertiserId" label="编号" ></el-table-column>
          <el-table-column prop="companyName" label="公司名称"></el-table-column>
          <el-table-column prop="contactPerson" label="联系人"></el-table-column>
          <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
          <el-table-column prop="contactEmail" label="邮箱"></el-table-column>
          <el-table-column prop="credit" label="信用额度"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" >
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tooltip :content="row.status === 1 ? '正常' : '封禁'" placement="top">
                <el-switch
                    v-model="row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="newStatus => handleSwitchChange(row, newStatus)">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template #default="{ row }">
              <el-link type="primary" @click="handleView(row)">查看</el-link>
              <el-divider direction="vertical" />
              <el-link type="danger" @click="handleDelete(row)">删除</el-link>
              <el-divider direction="vertical" />
              <el-link type="success" @click="handleEdit(row)">编辑</el-link>
            </template>
          </el-table-column>
        </el-table>

  <!--      分页-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </el-card>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
          title="广告信息"
          v-model="dialogVisible"
          width="50%"
      >
        <el-form :model="form" label-width="120px">
          <el-form-item label="用户id" :style="{ display: 'none'}">
            <el-input v-model="form.userId"></el-input>
          </el-form-item>
          <el-form-item label="公司名称" >
            <el-input
                v-model="form.companyName"
                placeholder="请输入公司名称"
                :disabled="isViewMode"></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input
                v-model="form.contactPerson"
                placeholder="请输入联系人"
                :disabled="isViewMode"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input
                v-model="form.contactPhone"
                placeholder="请输入联系电话"
                :disabled="isViewMode"></el-input>
          </el-form-item>
          <el-form-item label="联系邮箱">
            <el-input
                v-model="form.contactEmail"
                placeholder="请输入联系邮箱"
                :disabled="isViewMode"></el-input>
          </el-form-item>
          <el-form-item label="信用额度">
            <el-input
                v-model="form.credit"
                :disabled="isViewMode"></el-input>
          </el-form-item>
          <el-form-item label="创建时间" v-if="isViewMode">
            <template #default="{ row }">
              {{ formatDate(form.createTime) }}
            </template>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
                :disabled="isViewMode"
                v-model="form.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0">
            </el-switch>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">{{ isViewMode ? '关闭' : '取消'}}</el-button>
            <el-button type="primary" @click="handleSave" v-if="!isViewMode">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>

  <script>
  import axios from '@/utils/request';
  const jsonUser = localStorage.getItem('userInfo')
  const userInfo = JSON.parse(jsonUser)
  export default {
    name: 'AdList',
    data() {
      return {
        filterForm: {
          companyName: '',
          status: ''
        },
        isViewMode:false,
        loading: true,
        adList: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        dialogVisible: false,
        // 表单数据（新增/编辑用）
        form: {
          advertiserId: '',
          userId: '',
          companyName: '',
          contactPerson: '',
          contactPhone: '',
          contactEmail: '',
          credit: 0,
          status: '',
          createTime: '',
        }
      }
    },
    mounted() {
      this.getAdList();
    },
    methods: {
      // 获取列表
      getAdList() {
        this.loading = false;
        axios.get('/ad/page', {
          params: {
            companyName: this.filterForm.companyName,
            status: this.filterForm.status,
            current: this.currentPage,
            size: this.pageSize
          }
        }).then(response => {
          if (response.data.code === 200) {
            this.adList = response.data.data.records;
            this.total = response.data.data.total;
          } else {
            this.$message.error(response.data.message || '获取列表失败');
          }
        })
      },

      // 搜索
      searchUsers() {
        this.currentPage = 1;
        this.getAdList();
      },

      // 重置过滤条件
      resetFilter() {
        this.filterForm = {
          companyName: '',
          status: ''
        };
        this.currentPage = 1;
        this.getAdList();
      },

      // 处理分页大小变化
      handleSizeChange(size) {
        this.pageSize = size;
        this.getAdList();
      },

      // 处理当前页变化
      handleCurrentChange(page) {
        this.currentPage = page;
        this.getAdList();
      },

      // 格式化日期
      formatDate(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
      },

      // 新增
      handleAdd() {
        this.dialogVisible = true
        this.form = {
          advertiserId: '',
          userId: userInfo.userId,
          companyName: '',
          contactPerson: '',
          contactPhone: '',
          contactEmail: '',
          credit: 0,
          status: '',
          createTime: '',
        }
        this.isViewMode = false
      },
      // 编辑
      handleEdit(row) {
        this.dialogVisible = true
        this.isViewMode = false
        this.form = {...row}
      },
      //查看
      handleView(row){
        this.dialogVisible = true
        this.isViewMode = true;
        this.form = {...row}
      },


      // 处理删除
      handleDelete(row) {
        if (row.status === 1) {
          this.$message.warning('请先禁用广告主再删除');
          return;
        }
        this.$confirm('此操作将永久删除该记录，同时删除关联的广告计划和广告创意, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.delete('/ad/delete',{
            params:{
              advertiserId: row.advertiserId
            }
          }).then( () =>{
            const index = this.adList.findIndex(item => item.advertiserId === row.advertiserId)
            if (index !== -1) {
              this.adList.splice(index, 1)
            }
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },

      // 保存（新增/编辑）
      handleSave() {
        // 简单校验，可根据实际需求完善
        if (!this.form.companyName) {
          this.$message.error('请输入公司名称')
          return
        }
        if (!this.form.contactPerson) {
          this.$message.error('请输入联系人')
          return
        }
        // 发送请求
        axios.post('/ad/saveOrUpdate', this.form,)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(this.form.advertiserId ? '修改成功' : '添加成功');
                this.dialogVisible = false;
                // 刷新列表
                this.handleCurrentChange(this.currentPage);
                this.dialogVisible = false;
              } else {
                this.$message.error(response.data.message || '操作失败，请重试');
              }
            })
      },
      // 状态切换处理函数
      handleSwitchChange(ad, newStatus) {
        const action = newStatus === 0 ? '禁用' : '启用';
        const statusText = newStatus === 0 ? '禁用' : '正常';

        this.$confirm(`确定要${action}该广告主吗？此操作将${newStatus === 0 ? '同时暂停' : '同时启用'}其所有广告计划`, '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.post(`/ad/updateStatus?advertiserId=${ad.advertiserId}&status=${newStatus}`).then(response => {
            if (response.data.code == 200) {
              this.$message.success(`状态已更新为: ${statusText}`);
            } else {
              ad.status = ad.status === 1 ? 0 : 1;
              this.$message.error('状态更新失败: ' + response.data.message);
            }
          }).catch(error => {
            ad.status = ad.status === 1 ? 0 : 1;
            this.$message.error('请求失败: ' + error.message);
          });
        }).catch(() => {
          ad.status = ad.status === 1 ? 0 : 1;
          this.$message.info('操作已取消');
        });
      }


    }
  }
  </script>

  <style scoped>
  .user-list {
    padding: 20px;
  }

  .filter-card {
    margin-bottom: 20px;
  }

  </style>
